package com.atguigu.tingshu.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.shaded.com.google.gson.JsonObject;
import com.atguigu.tingshu.account.client.UserAccountFeignClient;
import com.atguigu.tingshu.account.client.impl.UserAccountDegradeFeignClient;
import com.atguigu.tingshu.album.client.AlbumInfoFeignClient;
import com.atguigu.tingshu.album.client.TrackInfoFeignClient;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.common.rabbit.service.RabbitService;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.order.OrderDerate;
import com.atguigu.tingshu.model.order.OrderDetail;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.model.user.VipServiceConfig;
import com.atguigu.tingshu.order.helper.SignHelper;
import com.atguigu.tingshu.order.mapper.OrderDerateMapper;
import com.atguigu.tingshu.order.mapper.OrderDetailMapper;
import com.atguigu.tingshu.order.mapper.OrderInfoMapper;
import com.atguigu.tingshu.order.service.OrderInfoService;
import com.atguigu.tingshu.user.client.UserInfoFeignClient;
import com.atguigu.tingshu.user.client.VipServiceConfigFeignClient;
import com.atguigu.tingshu.vo.account.AccountDeductVo;
import com.atguigu.tingshu.vo.order.OrderDerateVo;
import com.atguigu.tingshu.vo.order.OrderDetailVo;
import com.atguigu.tingshu.vo.order.OrderInfoVo;
import com.atguigu.tingshu.vo.order.TradeVo;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private UserInfoFeignClient userInfoFeignClient;

    @Autowired
    private AlbumInfoFeignClient albumInfoFeignClient;

    @Autowired
    private VipServiceConfigFeignClient vipServiceConfigFeignClient;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private TrackInfoFeignClient trackInfoFeignClient;

    @Autowired
    private RabbitService rabbitService;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private OrderDerateMapper orderDerateMapper;

    @Autowired
    private UserAccountFeignClient userAccountFeignClient;





    /**
     * 订单详情页
     * 专辑：{"itemType":"1001","itemId":1} itemId=album_info.id;
     * 声音：{"itemType":"1002","itemId":1}
     * vip: {"itemType":"1003","itemId":1} itemId=vip_service_config.id;
     * 要先判断是那一个订单的详情页（专辑，声音，vip）
     * @param tradeVo
     * @return
     */
    @Override
    public OrderInfoVo trade(Long userId, TradeVo tradeVo) {
        //本质在干啥? 给当前这个对象中的属性赋值：
        OrderInfoVo orderInfoVo = new OrderInfoVo();
        //原始金额
        BigDecimal originalAmount = new BigDecimal("0.00");
        //减免金额
        BigDecimal derateAmount = new BigDecimal("0.00");
        //实际价格
        BigDecimal orderAmount = new BigDecimal("0.00");
        //订单明细
        List<OrderDetailVo> orderDetailVoList = new ArrayList<>();
        //减免明细
        List<OrderDerateVo> orderDerateVoList = new ArrayList<>();

        //远程调用获得用户信息
        Result<UserInfoVo> userInfoVoResult = userInfoFeignClient.getUserInfoVo(userId);
        Assert.notNull(userInfoVoResult,"查询用户信息失败");
        UserInfoVo userInfoVo = userInfoVoResult.getData();
        Assert.notNull(userInfoVo,"查询用户信息失败");


        //判断订单是什么类型
        if(tradeVo.getItemType().equals(SystemConstant.ORDER_ITEM_TYPE_ALBUM)){
            //判断专辑是否被购买
            Result<Boolean> isPaidAlbumResult = userInfoFeignClient.isPaidAlbum(tradeVo.getItemId());
            Assert.notNull(isPaidAlbumResult, "查询用户是否购买专辑失败");
            Boolean result = isPaidAlbumResult.getData();
            if(result){
                //用户购买过专辑
                throw new GuiguException(ResultCodeEnum.REPEAT_BUY_ERROR);
            }
            //远程调用获取专辑信息
            Result<AlbumInfo> albumInfoResult = albumInfoFeignClient.getAlbumInfo(tradeVo.getItemId());//此时itemId是专辑id;
            Assert.notNull(albumInfoResult,"查询用户是否购买专辑失败");
            AlbumInfo albumInfo = albumInfoResult.getData();
            Assert.notNull(albumInfo,"查询用户是否购买专辑失败");
            //  获取到原价;
            originalAmount = albumInfo.getPrice();
            //是购买专辑的订单，需要判断购买专辑是不是有折扣和购买的和用户是不是vip和vip是否过期
            if(userInfoVo.getIsVip().intValue()==1 && userInfoVo.getVipExpireTime().after(new Date())){
                if(albumInfo.getVipDiscount().compareTo(new BigDecimal("-1"))>0){
                    //说明专辑有折扣
                    //用户是vip且没有过期，走vip折扣
                    //减免价格(保留两位小数，四舍五入模式)
                    derateAmount = albumInfo.getPrice().multiply(new BigDecimal("10").subtract(albumInfo.getVipDiscount())).divide(new BigDecimal("10"), 2, RoundingMode.HALF_UP);
                }
            }else {
                //用户不是vip，走普通折扣
                if (albumInfo.getDiscount().compareTo(new BigDecimal("-1")) > 0) {
                    //说明专辑有折扣
                    //减免价格
                    derateAmount = albumInfo.getPrice().multiply(new BigDecimal("10").subtract(albumInfo.getDiscount())).divide(new BigDecimal("10"), 2, RoundingMode.HALF_UP);
                }
            }
            //实际价格
            orderAmount=originalAmount.subtract(derateAmount);
            //订单明细
            //创建订单明细对象
            OrderDetailVo orderDetailVo = new OrderDetailVo();
            orderDetailVo.setItemId(tradeVo.getItemId());
            orderDetailVo.setItemName(albumInfo.getAlbumTitle());
            orderDetailVo.setItemUrl(albumInfo.getCoverUrl());
            orderDetailVo.setItemPrice(orderAmount);
            orderDetailVoList.add(orderDetailVo);
            //减免明细,先判断有没有减免
            if(derateAmount.compareTo(new BigDecimal("0.00"))>0){
                //说明有减免
                OrderDerateVo orderDerateVo=new OrderDerateVo();
                orderDerateVo.setDerateAmount(derateAmount);
                orderDerateVo.setDerateType(SystemConstant.ORDER_DERATE_ALBUM_DISCOUNT);// 专辑折扣
                orderDerateVo.setRemarks("专辑折扣");
                orderDerateVoList.add(orderDerateVo);
            }
        } else if (tradeVo.getItemType().equals(SystemConstant.ORDER_ITEM_TYPE_TRACK)) {
            //购买声音的订单，声音没有折扣，没有减免金额和减免明细
            //  判断：当前传递的声音数量：
            if (tradeVo.getTrackCount() < 0) {
                throw new GuiguException(ResultCodeEnum.ARGUMENT_VALID_ERROR);
            }
            //当前声音数量>=0; 计算金额+订单明细{声音不包含减免}
            //远程调用获取需要付费的声音列表
            Result<List<TrackInfo>> trackInfoListResult = trackInfoFeignClient.findPaidTrackInfoList(tradeVo.getItemId(), tradeVo.getTrackCount());
            Assert.notNull(trackInfoListResult, "查询声音信息失败");
            //  付费的声音列表;
            List<TrackInfo> trackInfoList = trackInfoListResult.getData();
            //获取到声音对象
            Result<TrackInfo> trackInfoResult = trackInfoFeignClient.getTrackInfo(tradeVo.getItemId());
            Assert.notNull(trackInfoResult, "查询声音信息失败");
            TrackInfo trackInfo = trackInfoResult.getData();
            Assert.notNull(trackInfo, "查询声音信息失败");
            //远程调用获取专辑对象（获取到声音价格）
            Result<AlbumInfo> albumInfoResult = albumInfoFeignClient.getAlbumInfo(trackInfo.getAlbumId());
            Assert.notNull(albumInfoResult, "查询专辑信息失败");
            AlbumInfo albumInfo = albumInfoResult.getData();
            Assert.notNull(albumInfo, "查询专辑信息失败");
            //  原始金额：购买本集传递的count=0;
            originalAmount=0==tradeVo.getTrackCount()?albumInfo.getPrice():albumInfo.getPrice().multiply(new BigDecimal(String.valueOf(tradeVo.getTrackCount())));
            orderAmount = originalAmount;
            //构建订单明细
            for (TrackInfo info : trackInfoList) {
                //  创建订单明细对象
                OrderDetailVo orderDetailVo = new OrderDetailVo();
                orderDetailVo.setItemPrice(albumInfo.getPrice());
                orderDetailVo.setItemName(info.getTrackTitle());
                orderDetailVo.setItemUrl(info.getCoverUrl());
                //  细节记住：属于购买声音的Id，并不是页面传递的声音Id;
                orderDetailVo.setItemId(info.getId());
                orderDetailVoList.add(orderDetailVo);
            }
        }else {
            //用户购买vip的订单
            Long itemId = tradeVo.getItemId();//此时itemId是vip_service_config.id;
            Result<VipServiceConfig> vipServiceConfigResult = vipServiceConfigFeignClient.getVipServiceConfig(itemId);
            Assert.notNull(vipServiceConfigResult, "查询vip服务配置失败");
            VipServiceConfig vipServiceConfig = vipServiceConfigResult.getData();
            Assert.notNull(vipServiceConfig, "查询vip服务配置失败");
            //原始价格
            originalAmount=vipServiceConfig.getPrice();
            //减免价格
            derateAmount = originalAmount.subtract(vipServiceConfig.getDiscountPrice());
            //实际价格
            orderAmount=vipServiceConfig.getDiscountPrice();
            //订单明细列表
            //创建订单明细对象
            OrderDetailVo orderDetailVo = new OrderDetailVo();
            orderDetailVo.setItemId(itemId);
            orderDetailVo.setItemName(vipServiceConfig.getName());
            orderDetailVo.setItemUrl(vipServiceConfig.getImageUrl());
            orderDetailVo.setItemPrice(orderAmount);
            orderDetailVoList.add(orderDetailVo);
            //减免明细列表
            if(derateAmount.compareTo(new BigDecimal("0.00"))>0){
                //说明有减免
                OrderDerateVo orderDerateVo=new OrderDerateVo();
                orderDerateVo.setDerateAmount(derateAmount);
                orderDerateVo.setDerateType(SystemConstant.ORDER_DERATE_VIP_SERVICE_DISCOUNT);// vip折扣
                orderDerateVo.setRemarks("vip服务折扣");
                orderDerateVoList.add(orderDerateVo);
            }
        }


        //给orderInfoVo对象赋值
        String tradeNo= UUID.randomUUID().toString().replaceAll("-","");
        //防止用户重复提交订单,将流水号存入订单中，提交订单时去缓存中看是否有tradeNo，若有说明重复提交
        String tradeNoKey = userId + ":" + tradeNo;
        redisTemplate.opsForValue().setIfAbsent(tradeNoKey, tradeNo,3, TimeUnit.MINUTES);
        orderInfoVo.setTradeNo(tradeNo);
        orderInfoVo.setPayWay("");
        orderInfoVo.setItemType(tradeVo.getItemType());
        orderInfoVo.setOriginalAmount(originalAmount);
        orderInfoVo.setDerateAmount(derateAmount);
        orderInfoVo.setOrderAmount(orderAmount);
        orderInfoVo.setOrderDetailVoList(orderDetailVoList);
        orderInfoVo.setOrderDerateVoList(orderDerateVoList);
        orderInfoVo.setTimestamp(SignHelper.getTimestamp());
        //签名的目的是为了防止用户非法篡改数据保证接口的安全性!
        //将订单信息对象orderInfoVo转换为 JSON 字符串
        String orderJson = JSONObject.toJSONString(orderInfoVo);
        //使用SignHelper.getSign()方法对 JSON 字符串解析后的 Map 对象生成签名
        //使用Map，标准化数据格式，让签名生成过程更稳定、可预期，避免因数据结构差异导致签名不一致
        String sign = SignHelper.getSign(JSONObject.parseObject(orderJson, Map.class));
        orderInfoVo.setSign(sign);
        return orderInfoVo;
    }

    /**
     * 提交订单，返回的是订单编号
     * 1、校验签名
     * 2、防止重复下单
     * 3、判断下单类型
     * @param orderInfoVo
     * @param userId
     * @return
     */
    @Override
    public String submitOrder(OrderInfoVo orderInfoVo, Long userId) {
        //1、校验签名,保证数据接口安全性! 校验orderInfoVo数据是否被篡改
        //orderInfoVo变为map集合;
        Map map = JSONObject.parseObject(JSON.toJSONString(orderInfoVo), Map.class);
        map.put("payWay", "");
        SignHelper.checkSign(map);

        //2、防止重复下单
        //2.1 获取当前页面传递的流水号;
        String tradeNo = orderInfoVo.getTradeNo();
        //2.2 与redis缓存中的流水号进行比较; 单线程-直接使用equals(); 多线程：redis+lua
        /*
        逻辑：
            前端提交订单时生成唯一 tradeNo，并先存入 Redis（通常在页面加载时）。
            后端通过 Lua 脚本原子性检查：若 Redis 中存在该 tradeNo 且值匹配，则删除它（表示首次提交）；否则返回 0（表示重复提交）。
            若 count == 0，则抛出 “重复提交” 异常，防止用户多次点击提交按钮导致重复下单
         */
        //redisTemplate.execute()方法将 Lua 脚本发送到 Redis 服务器执行，确保脚本内的所有操作原子性完成（不会被其他请求中断）

        String scriptText = "if redis.call(\"get\",KEYS[1]) == ARGV[1]\n" +
                "then\n" +
                "    return redis.call(\"del\",KEYS[1])\n" +
                "else\n" +
                "    return 0\n" +
                "end";
        String tradeNoKey = userId + ":" + tradeNo;
        //创建Redis脚本执行器
        DefaultRedisScript defaultRedisScript = new DefaultRedisScript<>();
        defaultRedisScript.setScriptText(scriptText); // 设置Lua脚本内容
        defaultRedisScript.setResultType(Long.class); // 指定脚本返回值类型（Long）
        //执行脚本
        Long count = (Long) redisTemplate.execute(
                defaultRedisScript,
                Arrays.asList(tradeNoKey), // KEYS参数：Redis键的列表（这里只有一个键）
                tradeNo // ARGV参数：对比的值（这里是前端传入的流水号）
        );
        //判断
        if (0 == count) {
            //说明重复提交
            //抛出异常;
            throw new GuiguException(ResultCodeEnum.REPEAT_SUBMIT);
        }

        //说明redis中没有订单号，说明没有重复提交
        //声明一个订单编号;
        String orderNo = UUID.randomUUID().toString().replaceAll("-", "");
        //3、判断用户选择的支付方式：在线，余额
        String payWay = orderInfoVo.getPayWay();
        if(!orderInfoVo.getPayWay().equals(SystemConstant.ORDER_PAY_ACCOUNT)){
            //不是账户余额=在线支付（微信支付）
            //保存订单交易记录
            saveOrderInfo(orderInfoVo, userId, orderNo);

            //发送延迟消息,发送延迟队列消息取消订单;
            rabbitService.sendDealyMessage(MqConst.EXCHANGE_CANCEL_ORDER, MqConst.ROUTING_CANCEL_ORDER, orderNo, MqConst.CANCEL_ORDER_DELAY_TIME);

        }else {
            // 余额支付，当用户选择 “余额支付” 时，系统需要先检查用户账户余额是否充足，扣减对应金额，然后将订单状态更新为 “已支付”
            // 需要一个远程调用;
            //检查与锁定账户金额
            //AccountDeductVo 是一个数据传输对象（DTO），用于封装扣减余额所需的所有信息
            AccountDeductVo accountDeductVo = new AccountDeductVo();
            accountDeductVo.setOrderNo(orderNo);       // 订单编号（关联订单）
            accountDeductVo.setUserId(userId);         // 用户ID（指定扣减哪个用户的余额）
            accountDeductVo.setAmount(orderInfoVo.getOrderAmount()); // 扣减金额（订单总金额）
            accountDeductVo.setContent("订单支付");    // 扣减备注（用于账户流水记录）

            //  远程调用;
            Result result = userAccountFeignClient.checkAndDeduct(accountDeductVo);
            //  判断；
            if (200 != result.getCode()) {
                throw new GuiguException(result.getCode(), result.getMessage());
            }
            //  保存订单数据
            saveOrderInfo(orderInfoVo, userId, orderNo);
            //  需要修改订单状态;
            OrderInfo orderInfo = new OrderInfo();
            orderInfo.setOrderStatus(SystemConstant.ORDER_STATUS_PAID);
            orderInfoMapper.update(orderInfo, new QueryWrapper<OrderInfo>().eq("order_no", orderNo));

            //  记录交易记录;远程调用userInfoFeinClient;
            UserPaidRecordVo userPaidRecordVo = new UserPaidRecordVo();
            userPaidRecordVo.setUserId(userId);
            userPaidRecordVo.setOrderNo(orderNo);
            userPaidRecordVo.setItemType(orderInfoVo.getItemType());
            List<Long> itemIdList = orderInfoVo.getOrderDetailVoList().stream().map(OrderDetailVo::getItemId).collect(Collectors.toList());
            userPaidRecordVo.setItemIdList(itemIdList);
            //  远程调用：
            Result userResult = userInfoFeignClient.savePaidRecord(userPaidRecordVo);
            //  判断
            if (200 != userResult.getCode()) {
                throw new GuiguException(211, "新增购买记录异常");
            }
        }

        return orderNo;
    }

    /**
     * 取消订单
     * @param orderNo
     */
    @Override
    public void cancelOrder(String orderNo) {
        //根据订单号查询订单
        OrderInfo orderInfo=this.getOrderInfoByOrderNo(orderNo);
        if(null == orderInfo){
            log.info("订单不存在：{}", orderNo);
            return;
        }
        //在修改订单状态之前再确认一遍用户没有支付
        if(orderInfo.getOrderAmount().equals(SystemConstant.ORDER_STATUS_PAID)){
            //用户支付了所以不取消订单
            log.info("订单已支付：{}", orderNo);
            return;
        }
        //在取消订单，将订单状态修改为已取消
        orderInfo.setOrderStatus(SystemConstant.ORDER_STATUS_CANCEL);
        this.updateById(orderInfo);
    }

    /**
     * 根据订单号查询订单
     * @param orderNo
     * @return
     */
    public OrderInfo getOrderInfoByOrderNo(String orderNo) {
        OrderInfo orderInfo = orderInfoMapper.selectOne(new LambdaQueryWrapper<OrderInfo>().eq(OrderInfo::getOrderNo, orderNo));
        if(null!=orderInfo){
            String payName=orderInfo.getPayWay().equals(SystemConstant.ORDER_PAY_ACCOUNT)?"余额":"在线";
            //设置支付名称
            orderInfo.setPayWayName(payName);
        }
        //返回数据
        return orderInfo;
    }



    /**
     * 保存订单交易记录
     * 保存订单，明细，免减
     * @param orderInfoVo
     * @param userId
     * @param orderNo
     */
    @Transactional(rollbackFor = Exception.class)
    private void saveOrderInfo(OrderInfoVo orderInfoVo, Long userId, String orderNo) {
        //保存进订单表
        OrderInfo orderInfo = new OrderInfo();
        //属性赋值
        BeanUtils.copyProperties(orderInfoVo,orderInfo);
        //orderInfoVo属性值不全，在orderInfo中给orderInfoVo没有的属性赋值
        orderInfo.setUserId(userId);
        orderInfo.setOrderTitle(orderInfoVo.getOrderDetailVoList().get(0).getItemName());
        orderInfo.setOrderNo(orderNo);
        orderInfo.setOrderStatus(SystemConstant.ORDER_STATUS_UNPAID);//未支付
        orderInfoMapper.insert(orderInfo);

        //保存进订单明细表
        List<OrderDetailVo> orderDetailVoList = orderInfoVo.getOrderDetailVoList();
        if(!CollectionUtils.isEmpty(orderDetailVoList)){
            for (OrderDetailVo orderDetailVo : orderDetailVoList) {
                //  创建对象
                OrderDetail orderDetail = new OrderDetail();
                orderDetail.setOrderId(orderInfo.getId());
                orderDetail.setItemId(orderDetailVo.getItemId());
                orderDetail.setItemName(orderDetailVo.getItemName());
                orderDetail.setItemUrl(orderDetailVo.getItemUrl());
                orderDetail.setItemPrice(orderDetailVo.getItemPrice());
                orderDetailMapper.insert(orderDetail);
            }
        }
        //保存进订单减免表
        List<OrderDerateVo> orderDerateVoList = orderInfoVo.getOrderDerateVoList();
        if(!CollectionUtils.isEmpty(orderDerateVoList)){
            for (OrderDerateVo orderDerateVo : orderDerateVoList) {
                OrderDerate orderDerate = new OrderDerate();
                orderDerate.setOrderId(orderInfo.getId());
                orderDerate.setDerateType(orderDerateVo.getDerateType());
                orderDerate.setDerateAmount(orderDerateVo.getDerateAmount());
                orderDerate.setRemarks(orderDerateVo.getRemarks());
                orderDerateMapper.insert(orderDerate);
            }
        }
    }

    /**
     * 根据状态查看我的订单
     * @param orderInfoPage
     * @param orderStatus
     * @param userId
     * @return
     */
    @Override
    public IPage<OrderInfo> findUserPage(Page<OrderInfo> orderInfoPage, String orderStatus, Long userId) {
        //调用mapper层方法
        IPage<OrderInfo> iPage = orderInfoMapper.selectUserPage(orderInfoPage, userId, orderStatus);
        //遍历订单记录列表，为每个订单对象设置订单状态名称和支付方式名称的中文显示文本
        iPage.getRecords().forEach(orderInfo -> {
            String orderStatusName =orderInfo.getOrderStatus().equals(SystemConstant.ORDER_STATUS_UNPAID)?"未支付":orderInfo.getOrderStatus().equals(SystemConstant.ORDER_STATUS_PAID)?"已支付":"取消订单";
            orderInfo.setOrderStatusName(orderStatusName);
            orderInfo.setPayWayName(orderInfo.getPayWay().equals(SystemConstant.ORDER_PAY_ACCOUNT)?"余额":"在线");
        });
        return iPage;
    }

    /**
     * 订单支付成功，修改订单状态
     * @param orderNo
     */
    @Override
    public void orderPaySuccess(String orderNo) {
        //根据订单编号获取订单详情
        OrderInfo orderInfo = orderInfoMapper.selectOne(new LambdaQueryWrapper<OrderInfo>().eq(OrderInfo::getOrderNo, orderNo));
        //判断
        if (null != orderInfo && orderInfo.getOrderStatus().equals(SystemConstant.ORDER_STATUS_UNPAID)) {
            //修改状态;
            orderInfo.setOrderStatus(SystemConstant.ORDER_STATUS_PAID);
            this.updateById(orderInfo);

            //远程调用需要userPaidRecordVo对象，所以创建一个userPaidRecordVo
            UserPaidRecordVo userPaidRecordVo = new UserPaidRecordVo();
            //赋值
            userPaidRecordVo.setUserId(orderInfo.getUserId());
            userPaidRecordVo.setOrderNo(orderInfo.getOrderNo());
            userPaidRecordVo.setItemType(orderInfo.getItemType());
            //itemIdList
            List<Long> itemIdList = orderInfo.getOrderDetailList().stream().map(OrderDetail::getItemId).collect(Collectors.toList());
            userPaidRecordVo.setItemIdList(itemIdList);
            //订单支付成功后需要保存用户购买记录
            //保存用户购买记录;
            userInfoFeignClient.savePaidRecord(userPaidRecordVo);
        }
    }
}
